*! calculate the total r2 = Corr(yhat,y)^2 after xt regression commands
*! version 1.0.0 9aug2021 by John Luke Gallup (jlgallup@pdx.edu)

program define xt_r2total, eclass
	version 11
	tempvar touse xbu ui
	_xt
	local id "`r(ivar)'"

	quietly {
		gen byte `touse' = e(sample)
		_predict double `xbu' if `touse', xb 
		sort `id' `touse'
		by `id' `touse': gen double `ui' = cond(`touse' & _n==_N, ///
			sum(`e(depvar)')/_n-sum(`xbu')/_n,.) if `touse'
		by `id': replace `xbu'= `xbu' + `ui'[_N] if `touse'
		local weight "[`e(wtype)'`e(wexp)']"
		qui corr `xbu' `e(depvar)' `weight' if `touse'
		noi di("R-squared (Corr[y,ŷ]^2) = `:display %4.2f `=(r(rho))^2''")
		ereturn	scalar r2_t = (r(rho))^2
	}
// display results
// check including in -estats-
end
